
import { defineStore } from 'pinia'
import { info, reqLogin } from '@/api/user/index.js'
import { ElMessage } from 'element-plus'
import { setToken, removeToken } from '@/util/auth.js'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userId: null,
    user: {},
    userInfo: null
  }),
  getters: {
    isLogin: (state) => !!state.token
  },
  actions: {
    async login(reqData) {
      const res = await reqLogin(reqData)
      const data = res.data
      if (res.code === 200) {
        localStorage.setItem('token', data.token)
        this.token = data.token
        this.user = data
        this.userId = data.userId
        this.userInfo = data
        setToken(this.token)
        ElMessage.success('登录成功')
      }
    },
    async info() {
      const res = await info()
      const data = res.data
      if (res.code === 200) {
        this.user = data
        this.userId = data.userId
        this.userInfo = data
      }
    },
    // 退出登录
    logout() {
      // 清除 state
      this.token = ''
      this.userId = null
      this.user = {}
      this.userInfo = null

      // 清除 localStorage
      localStorage.removeItem('token')
      localStorage.removeItem('userId')
      localStorage.removeItem('userInfo')

      // 清除 cookie 中的 token
      removeToken()

      ElMessage.success('已退出登录')
    },
    // 清除所有用户数据（用于登录失效等场景）
    clearUserData() {
      this.logout()
    }
  }
})
